﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace GameSetting.Global
{
    class ProgramExecutor
    {
        public static void ExecuteProgram(string programPath)
        {
            // 验证文件存在性
            if (!File.Exists(programPath))
            {
                throw new FileNotFoundException("目标程序不存在", programPath);
            }

            // Linux系统权限处理
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) && !HasExecutePermission(programPath))
            {
                SetExecutePermission(programPath);
            }

            // 启动进程
            using var process = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName = programPath,
                    UseShellExecute = true,
                    CreateNoWindow = false,
                    RedirectStandardOutput = false,
                    RedirectStandardError = false
                }
            };

            if (!process.Start())
            {
                throw new InvalidOperationException($"进程启动失败: {programPath}");
            }
        }

        private static bool HasExecutePermission(string path)
        {
            var mode = new FileInfo(path).UnixFileMode;
            return (mode & System.IO.UnixFileMode.UserExecute) != 0 ||
                   (mode & System.IO.UnixFileMode.GroupExecute) != 0 ||
                   (mode & System.IO.UnixFileMode.OtherExecute) != 0;
        }

        private static void SetExecutePermission(string path)
        {
            using var chmod = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName = "/bin/bash",
                    Arguments = $"-c \"chmod +x {path}\"",
                    RedirectStandardError = true,
                    UseShellExecute = false,
                    CreateNoWindow = true
                }
            };

            chmod.Start();
            chmod.WaitForExit();

            if (chmod.ExitCode != 0)
            {
                throw new IOException($"权限设置失败: {chmod.StandardError.ReadToEnd()}");
            }
        }
    }
}
